//
//  Reply.m
//  LilyBBS
//
//  Created by 李行 on 11-11-28.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "Reply.h"
#import "SingleCookie.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "RegexKitLite.h"
#import "Top10Detail.h"
#import "ExpressionViewController.h"
#import "Reachability.h"
#import <QuartzCore/QuartzCore.h>

@implementation Reply

@synthesize replies,urlString,pid,url,expbtn,replybtn,cancelbtn,expressionbtn,reptitle;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    //self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(done:)];
    //self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancel:)];
    return self;
    

}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle



- (void)viewDidLoad
{
    [super viewDidLoad];
    //[self.replies becomeFirstResponder];
    replies = [[UITextView alloc] initWithFrame:CGRectMake(20, 22, 260, 90)];
    //[self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]]];
    [self.view setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:0.75]];
    /*边框*/
    [replies setBackgroundColor:[UIColor whiteColor]];
    replies.layer.cornerRadius=4;
    replies.layer.masksToBounds=YES;
    replies.layer.borderWidth=0;
    replies.layer.borderColor=[[UIColor colorWithRed:0.25 green:0.25 blue:0.25 alpha:1] CGColor];
    
    reptitle = [[UITextView alloc] init];
    /*[reptitle setBackgroundColor:[UIColor whiteColor]];
    reptitle.layer.cornerRadius=4;
    reptitle.layer.masksToBounds=YES;
    reptitle.layer.borderWidth=0;
    reptitle.layer.borderColor=[[UIColor colorWithRed:0.25 green:0.25 blue:0.25 alpha:1] CGColor];*/
    
    /*mytitle = [[UILabel alloc] initWithFrame:CGRectMake(20, 15, 50,30)];
    mytitle.text = @" 标题";
    mytitle.backgroundColor=[UIColor clearColor];
    mytitle.textColor = [UIColor whiteColor];*/
    
    //[self.view setBackgroundColor:[UIColor whiteColor]];
    self.view.layer.borderWidth = 0;
    self.view.layer.borderColor = [[UIColor grayColor] CGColor];
    self.view.layer.cornerRadius=4;
    self.view.layer.masksToBounds=YES;
    
    replybtn = [UIButton buttonWithType:UIButtonTypeCustom];
    replybtn.frame =CGRectMake(220, 122, 60, 28);
    [replybtn setTitle:@"回复" forState:UIControlStateNormal];
    [replybtn addTarget:self action:@selector(done:) forControlEvents:UIControlEventTouchUpInside];
    
    cancelbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelbtn.frame = CGRectMake(20, 122, 60, 28);
    [cancelbtn setTitle:@"取消" forState:UIControlStateNormal];
    //[cancelbtn addTarget:self action:@selector(cancel:) forControlEvents:UIControlEventTouchUpInside];
    
    expressionbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    expressionbtn.frame =CGRectMake(120, 122, 60, 28);
    [expressionbtn setTitle:@"表情" forState:UIControlStateNormal];
    [expressionbtn addTarget:self action:@selector(openexpression:) forControlEvents:UIControlEventTouchUpInside];
    
    backbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backbtn.frame =CGRectMake(120, 122, 60, 28);
    backbtn.hidden = YES;
    [backbtn setTitle:@"返回" forState:UIControlStateNormal];
    [backbtn addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
    
    

    
    
    _exp = [[ExpressionViewController alloc] init];
    [_exp.view setFrame:CGRectMake(0, 0, 0, 0)];
    
    
    
    //[self.view addSubview:mytitle];
    //[self.view addSubview:reptitle];
    [self.view addSubview:expressionbtn];
    [self.view addSubview:cancelbtn];
    [self.view addSubview:replybtn];
    [self.view addSubview:replies];
    [self.view addSubview:_exp.view];
    [_exp.view addSubview:backbtn];
   
    
    
    
    
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


-(void)openexpression:(id)sender{
    backbtn.hidden = NO;
    [_exp.view setFrame:CGRectMake(0 , 0, 300, 160)];
    [replies resignFirstResponder];
    
    
    if(biaoqing.superview ==nil){
    biaoqing = [[UIScrollView alloc] init];
    [biaoqing setFrame:CGRectMake(15, 10, 270, 100)];
    [biaoqing setBackgroundColor:[UIColor clearColor]];
    [biaoqing setContentSize:CGSizeMake(560, 100)];
    biaoqing.pagingEnabled = YES;
    [_exp.view addSubview:biaoqing];
    
    for (int i=0; i<3; i++) {
		//column numer
		for (int y=0; y<12; y++) {
			expbtn=[UIButton buttonWithType:UIButtonTypeCustom];
			NSString *imageName=[NSString stringWithFormat:@"%d",i*12+y+1];
			switch ([imageName length]) {
				case 1:
					imageName=[NSString stringWithFormat:@"00%@.gif",imageName];
					break;
				case 2:
					imageName=[NSString stringWithFormat:@"0%@.gif",imageName];
					break;
				default:
					break;
			}
			[expbtn setBackgroundColor:[UIColor clearColor]];
			[expbtn setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
                [expbtn setFrame:CGRectMake(10+45*y, 10+34*i, 22 , 22)];
			expbtn.tag=i*12+y;
            [biaoqing addSubview:expbtn];
			[expbtn addTarget:self action:@selector(expressionSelected:) forControlEvents:UIControlEventTouchUpInside];
		}
      }
    }
    
    CATransition *animation = [CATransition animation];
    
    animation.delegate = self;
    // 设定动画时间
    animation.duration = 0.5;
    // 设定动画快慢(开始与结束时较慢)
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    // 12种类型
    animation.type = @"rippleEffect";
    NSUInteger fir = [[self.view subviews] indexOfObject:self.view];
    NSUInteger sec = [[self.view subviews] indexOfObject:_exp.view];
    [self.view exchangeSubviewAtIndex:fir withSubviewAtIndex:sec];
    
    // 动画开始
    [[self.view layer] addAnimation:animation forKey:@"animation"];
    
    [self.view setBackgroundColor:[UIColor clearColor]];
    [replies setBackgroundColor:[UIColor clearColor]];
    //[reptitle setBackgroundColor:[UIColor clearColor]];
    replybtn.hidden = YES;

    replies.hidden = YES;
    cancelbtn.hidden = YES;
    expressionbtn.hidden = YES;
    //mytitle.hidden = YES;
    
}

-(void)expressionSelected:(UIButton*)bt{
    switch (bt.tag) {
        case 0:
            self.replies.text=[NSString stringWithFormat:@"%@[:s]",self.replies.text];
            break;
        case 1:
            self.replies.text=[NSString stringWithFormat:@"%@[:O]",self.replies.text];
            break;
        case 2:
            self.replies.text=[NSString stringWithFormat:@"%@[:|]",self.replies.text];
            break;
        case 3:
            self.replies.text=[NSString stringWithFormat:@"%@[:$]",self.replies.text];
            break;
        case 4:
            self.replies.text=[NSString stringWithFormat:@"%@[:X]",self.replies.text];
            break;
        case 5:
            self.replies.text=[NSString stringWithFormat:@"%@[:'(]",self.replies.text];
            break;
        case 6:
            self.replies.text=[NSString stringWithFormat:@"%@[:-|]",self.replies.text];
            break;
        case 7:
            self.replies.text=[NSString stringWithFormat:@"%@[:@]",self.replies.text];
            break;
        case 8:
            self.replies.text=[NSString stringWithFormat:@"%@[:P]",self.replies.text];
            break;
        case 9:
            self.replies.text=[NSString stringWithFormat:@"%@[:D]",self.replies.text];
            break;
        case 10:
            self.replies.text=[NSString stringWithFormat:@"%@[:)]",self.replies.text];
            break;
        case 11:
            self.replies.text=[NSString stringWithFormat:@"%@[:(]",self.replies.text];
            break;
        case 12:
            self.replies.text=[NSString stringWithFormat:@"%@[:Q]",self.replies.text];
            break;
        case 13:
            self.replies.text=[NSString stringWithFormat:@"%@[:T]",self.replies.text];
            break;
        case 14:
            self.replies.text=[NSString stringWithFormat:@"%@[;P]",self.replies.text];
            break;
        case 15:
            self.replies.text=[NSString stringWithFormat:@"%@[;-D]",self.replies.text];
            break;
        case 16:
            self.replies.text=[NSString stringWithFormat:@"%@[:!]",self.replies.text];
            break;
        case 17:
            self.replies.text=[NSString stringWithFormat:@"%@[:L]",self.replies.text];
            break;
        case 18:
            self.replies.text=[NSString stringWithFormat:@"%@[:?]",self.replies.text];
            break;
        case 19:
            self.replies.text=[NSString stringWithFormat:@"%@[:U]",self.replies.text];
            break;
        case 20:
            self.replies.text=[NSString stringWithFormat:@"%@[:K]",self.replies.text];
            break;
        case 21:
            self.replies.text=[NSString stringWithFormat:@"%@[:C-]",self.replies.text];
            break;
        case 22:
            self.replies.text=[NSString stringWithFormat:@"%@[;X]",self.replies.text];
            break;
        case 23:
            self.replies.text=[NSString stringWithFormat:@"%@[:H]",self.replies.text];
            break;
        case 24:
            self.replies.text=[NSString stringWithFormat:@"%@[;bye]",self.replies.text];
            break;
        case 25:
            self.replies.text=[NSString stringWithFormat:@"%@[;cool]",self.replies.text];
            break;
        case 26:
            self.replies.text=[NSString stringWithFormat:@"%@[:-b]",self.replies.text];
            break;
        case 27:
            self.replies.text=[NSString stringWithFormat:@"%@[:-8]",self.replies.text];
            break;
        case 28:
            self.replies.text=[NSString stringWithFormat:@"%@[;PT]",self.replies.text];
            break;
        case 29:
            self.replies.text=[NSString stringWithFormat:@"%@[:hx]",self.replies.text];
            break;
        case 30:
            self.replies.text=[NSString stringWithFormat:@"%@[;K]",self.replies.text];
            break;
        case 31:
            self.replies.text=[NSString stringWithFormat:@"%@[:E]",self.replies.text];
            break;
        case 32:
            self.replies.text=[NSString stringWithFormat:@"%@[:-(]",self.replies.text];
            break;
        case 33:
            self.replies.text=[NSString stringWithFormat:@"%@[;hx]",self.replies.text];
            break;
        case 34:
            self.replies.text=[NSString stringWithFormat:@"%@[:-v]",self.replies.text];
            break;
        case 35:
            self.replies.text=[NSString stringWithFormat:@"%@[;xx]",self.replies.text];
            break;
            
        default:
            break;
    }
    [_exp.view setFrame:CGRectMake(0 , 0, 0 , 0)];
    [replies becomeFirstResponder];
    
    
    CATransition *animation = [CATransition animation];
    
    animation.delegate = self;
    // 设定动画时间
    animation.duration = 0.5;
    // 设定动画快慢(开始与结束时较慢)
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    // 12种类型
    animation.type = @"rippleEffect";
    NSUInteger green = [[self.view subviews] indexOfObject:self.view];
    NSUInteger blue = [[self.view subviews] indexOfObject:_exp.view];
    [self.view exchangeSubviewAtIndex:green withSubviewAtIndex:blue];
    
    // 动画开始
    [[self.view layer] addAnimation:animation forKey:@"animation"];
    
    backbtn.hidden = YES;
    [self.view setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:0.75]];
    [replies setBackgroundColor:[UIColor whiteColor]];
    //[reptitle setBackgroundColor:[UIColor whiteColor]];

    replybtn.hidden = NO;
    cancelbtn.hidden = NO;
    replies.hidden = NO;
    expressionbtn.hidden = NO;
    //mytitle.hidden = NO;

}

-(void)back:(id)sender{
    [_exp.view setFrame:CGRectMake(0 , 0, 0 , 0)];
    [replies becomeFirstResponder];
    
    
    CATransition *animation = [CATransition animation];
    
    animation.delegate = self;
    // 设定动画时间
    animation.duration = 0.5;
    // 设定动画快慢(开始与结束时较慢)
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    // 12种类型
    animation.type = @"rippleEffect";
    NSUInteger green = [[self.view subviews] indexOfObject:self.view];
    NSUInteger blue = [[self.view subviews] indexOfObject:_exp.view];
    [self.view exchangeSubviewAtIndex:green withSubviewAtIndex:blue];
    
    // 动画开始
    [[self.view layer] addAnimation:animation forKey:@"animation"];
    
    backbtn.hidden = YES;
    [self.view setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:0.75]];
    [replies setBackgroundColor:[UIColor whiteColor]];
    //[reptitle setBackgroundColor:[UIColor whiteColor]];
    replybtn.hidden = NO;
    replies.hidden = NO;
    cancelbtn.hidden = NO;
    expressionbtn.hidden = NO;
    //mytitle.hidden = NO;

}

-(IBAction)done:(id)sender{
    Reachability *r = [Reachability reachabilityWithHostName:@"www.nju.edu.cn"];
    switch ([r currentReachabilityStatus]) {
        case NotReachable:
            //没有网络连接
            NSLog(@" ");
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络好像连接不上。。。" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [alert show];
            [alert release];
            return;
        case ReachableViaWWAN:
            //使用3G网络            
            break;
        case ReachableViaWiFi:
            // 使用WiFi网络            
            break;
    }
    
    if ([[SingleCookie sharedSingleCookie].savedCookies count]==0) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"回复提示" message:@"尚未登录，请登录后回复。" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
        return;
        //[self dismissModalViewControllerAnimated:YES];
    }
    
    //以用户身份发送回复
    NSString* partOfURL = [urlString stringByMatching:@"(?<=bbstcon)[\\w\\W]*"];
    NSString* preURL = [NSString stringWithFormat:@"http://bbs.nju.edu.cn/vd%@/bbspst",[SingleCookie sharedSingleCookie].randomNumber];
    NSString* realURL = [preURL stringByAppendingString:partOfURL];
     url = [NSURL URLWithString:realURL];
    NSString* pid = [self getPid];
    NSString* reid = [realURL stringByMatching:@"(?<=M.)[\\w\\W]*(?=.A)"];
    NSString* content = self.replies.text;
    NSString* titlecontent = self.reptitle.text;
    int max = [content length];
    int i;
    for (i = 0; i < max; i++)
    {
        unichar ch = [content characterAtIndex: i];
        printf("%x ", ch);
    }

    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000); 
    NSString* requestURLString1 = [realURL stringByMatching:@"[\\w\\W]*(?=&file=)"];
    NSString* requestURLString = [realURL stringByReplacingOccurrencesOfRegex:@"pst" withString:@"snd"];
    NSURL* requestURL = [NSURL URLWithString:requestURLString];
    
     ASIFormDataRequest* request = [ASIFormDataRequest requestWithURL:requestURL];
     [request setStringEncoding:enc];
     [request setUseCookiePersistence:NO];
     [request setRequestCookies:[SingleCookie sharedSingleCookie].savedCookies];
     //[request setPostValue:@"通过小百合iPhone客户端LilyBBS回复" forKey:@"title"];
     [request setPostValue:titlecontent forKey:@"title"];
     [request setPostValue:pid forKey:@"pid"];
     [request setPostValue:reid forKey:@"reid"];
     [request setPostValue:@"1" forKey:@"signature"];
     [request setPostValue:@"on" forKey:@"autocr"];
     [request setPostValue:content forKey:@"text"];
     [request startSynchronous];
    NSLog(@"request responseString:%@",[request responseString]);
    [UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:.4];
    [self.view setFrame:CGRectMake(10, -5, 300, 0)];
    [replies resignFirstResponder];
    [UIView commitAnimations];
    
    //[self becomeFirstResponder];
    //[self dismissModalViewControllerAnimated:YES];
}

-(void)cancel:(id)sender{
    [replies resignFirstResponder];
    [UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:.2];
    [self.view setFrame:CGRectMake(10, -5, 300, 0)];
	[UIView commitAnimations];
    
    [super dealloc];
    
    //[self becomeFirstResponder];
    //[self dismissModalViewControllerAnimated:YES];
}

-(NSString*)getPid{
    ASIHTTPRequest* request = [[ASIHTTPRequest alloc] initWithURL:url];
    [request setUseCookiePersistence:NO];
    [request setRequestCookies:[SingleCookie sharedSingleCookie].savedCookies];
    [request startSynchronous];
    NSData* data = [request responseData];
    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);   
    NSString* dataString = [[NSString alloc]initWithData:data encoding:enc];
    NSLog(@"dataString:%@",dataString);
    NSString* result = [dataString stringByMatching:@"(?<=name=pid value=')[\\w\\W]*(?='><input type=hidden name=reid)"];
    return result;
}

-(void)dealloc{
    [super dealloc];
}

@end
